# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/2/25 20:59
Author : 田霄汉
Email : 522989570@qq.com
File : yaml_util.py
Project : pytest_demo
=======================================
'''
import yaml
import os

class YamlUtil:

    # 获取testdata_yaml路径
    local_path = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "../")), "testdata_yaml")

    def read_yaml(self, yaml_name, key):
        """
        :param yaml_name: yaml文件名
        :param key: 需要读取的key值
        :return: 返回value值
        """

        # 定位到具体的yaml文件
        yaml_path = os.path.join(self.local_path, yaml_name)

        # 打开yaml文件
        with open(file=yaml_path, mode='r', encoding='utf-8') as f:
            content = yaml.load(stream=f, Loader=yaml.Loader)
            return content.get(key)

    def read_yaml_nokey(self, yaml_name):
        """
        :param yaml_name: yaml文件
        :return: 返回value值
        """

        # 定位到具体的yaml文件
        yaml_path = os.path.join(self.local_path, yaml_name)

        # 打开yaml文件
        with open(file=yaml_path, mode='r', encoding='utf-8') as f:
            content = yaml.load(stream=f, Loader=yaml.Loader)
            return content

    def write_yaml(self, data, yaml_name):
        """
        :param data: 写入yaml的数据
        :param yaml_name: yaml的名字
        :return: None
        """

        # 获取要写入的yaml路径
        yaml_path = os.path.abspath(os.path.join(self.local_path, yaml_name))

        # 将data写入yaml对应的key值
        with open(file=yaml_path, mode='w', encoding="utf-8") as f:
            yaml.dump(data=data, stream=f, Dumper=yaml.Dumper, allow_unicode=True)

    def write_yaml_add(self, data, yaml_name):
        """
        :param data: 写入yaml的数据
        :param yaml_name: yaml的名字
        :return: None
        """

        # 获取要写入的yaml路径
        yaml_path = os.path.abspath(os.path.join(self.local_path, yaml_name))

        # 将data写入yaml对应的key值
        with open(file=yaml_path, mode='a', encoding="utf-8") as f:
            yaml.dump(data=data, stream=f, Dumper=yaml.Dumper, allow_unicode=True)

    def clear_yaml(self, yaml_name):
        """
        :param yaml_name: yaml文件的目录
        :return:
        """
        # 获取要写入的yaml路径
        yaml_path = os.path.join(self.local_path, yaml_name)

        with open(file=yaml_path, mode="w", encoding="utf-8") as f:
            f.truncate()